package com.ysd.shopcar.common;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.ysd.shopcar.utils.JsonUtils;

/**
 * 基本处理程序
 */
public abstract class BaseProcesser<TRequest extends BaseRequestVO, TData> {
	private static final Logger LOGGER = LoggerFactory.getLogger(BaseProcesser.class);
	public static final String NEW_LINE = "\r\n";

	/**
	 * 处理程序
	 */
	public JSONResult<TData> process(TRequest request) {
		long beginTime = System.currentTimeMillis();
		JSONResult<TData> response = null;
		try {
			this.init(request);
			this.validate(request);
			response = this.processing(request);
		} catch (IllegalArgumentException e) {
			LOGGER.warn("Processer异常", e);
			response = JSONResult.build(HttpStatus.SC_BAD_REQUEST, e.getMessage(), null);
		} catch (CommonException e) {
			LOGGER.warn("Processer异常", e);
			response = JSONResult.build(e.getErrCode(), e.getMessage(), null);
		} catch (Exception e) {
			LOGGER.warn("Processer异常", e);
			response = JSONResult.build(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), null);
		} finally {
			long endTime = System.currentTimeMillis();
			String log = getProcessLog(endTime - beginTime, request, response);
			LOGGER.info(log);
			MDC.clear();
		}
		return response;
	}

	/**
	 * 初始化
	 */
	protected void init(TRequest request) {
	}

	/**
	 * 参数验证
	 */
	protected abstract void validate(TRequest request);

	/**
	 * 处理
	 */
	protected abstract JSONResult<TData> processing(TRequest request) throws Exception;

	/**
	 * 获取处理日志
	 */
	public static String getProcessLog(long processTime, Object request, Object response) {
		StringBuilder sb = new StringBuilder();
		sb.append("耗时：").append(processTime).append("毫秒").append(NEW_LINE);
		sb.append("入参：").append(NEW_LINE);
		sb.append(JsonUtils.toJSONString(request)).append(NEW_LINE);
		sb.append("出参：").append(NEW_LINE);
		sb.append(JsonUtils.toJSONString(response));
		return sb.toString();
	}

}